Looper 源码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static final void prepare() {
//判断sThreadLocal是否为null,否则抛出异常
//即Looper.prepare()方法不能被调用两次
//也就是说,一个线程中只能对应一个Looper实例
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//sThreadLocal是一个ThreadLocal对象,用于在一个线程中存储变量
//实例化Looper对象并存放在ThreadLocal
//这说明Looper是存放在Thread线程里的
sThreadLocal.set(new Looper(true));
}
//再来看下Looper的构造方法
private Looper(boolean quitAllowed) {
//创建了一个MessageQueue(消息队列)
//这说明,当创建一个Looper实例时,会自动创建一个与之配对的MessageQueue(消息队列)
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}

消息循环 Loop()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static void loop() {
//myLooper()方法作用是返回sThreadLocal存储的Looper实例,如果me为null,loop()则抛出异常
//也就是说loop方法的执行必须在prepare方法之后运行
//也就是说,消息循环必须要先在线程当中创建Looper实例
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取looper实例中的mQueue(消息队列)
final MessageQueue queue = me.mQueue;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
//进入消息循环
for (;;) {
//next()方法用于取出消息队列里的消息
//如果取出的消息为空,则线程阻塞
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//消息派发:把消息派发给msg的target属性,然后用dispatchMessage方法去处理
//Msg的target其实就是handler对象,下面会继续分析
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
//释放消息占据的资源
msg.recycle();
}
}

Handler 源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//通过Looper.myLooper()获取了当前线程保存的Looper实例,如果线程没有Looper实例那么会抛出异常
//这说明在一个没有创建Looper的线程中是无法创建一个Handler对象的
//所以说我们在子线程中创建一个Handler时首先需要创建Looper,并且开启消息循环才能够使用这个Handler。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获取了这个Looper实例中保存的MessageQueue(消息队列)
//这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

发送消息

  1. send的发送方法:sendMessage()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    public final boolean sendMessage(Message msg)
    {
    return sendMessageDelayed(msg, 0);
    }
    //我们往下扒
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
    if (delayMillis < 0) {
    delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //直接获取MessageQueue
    MessageQueue queue = mQueue;
    if (queue == null) {
    RuntimeException e = new RuntimeException(
    this + " sendMessageAtTime() called with no mQueue");
    Log.w("Looper", e.getMessage(), e);
    return false;
    }
    //调用了enqueueMessage方法
    return enqueueMessage(queue, msg, uptimeMillis);
    }
    //调用sendMessage方法其实最后是调用了enqueueMessage方法
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //为msg.target赋值为this,也就是把当前的handler作为msg的target属性
    //如果大家还记得Looper的loop()方法会取出每个msg然后执行msg.target.dispatchMessage(msg)去处理消息,其实就是派发给相应的Handler
    msg.target = this;
    if (mAsynchronous) {
    msg.setAsynchronous(true);
    }
    //最终调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去。
    return queue.enqueueMessage(msg, uptimeMillis);
    }
  2. Post 发送消息

    1
    2
    3
    4
    5
    6
    7
    8
    showhandler.post(new Runnable() {
    @Override
    public void run() {
    String line = "\n";
    StringBuffer text = new StringBuffer(show.getText());
    text.append(line).append("angelababy:Yes,I do");
    show.setText(text);
    }
  3. dispathMessage()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
    handleCallback(msg);
    } else {
    if (mCallback != null) {
    if (mCallback.handleMessage(msg)) {
    return;
    }
    }
    handleMessage(msg);
    }
    }
    public void handleMessage(Message msg) {
    }

在Activity启动应用的时候

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//一个进程会默认生成一个主线程
public static void main(String[] args) {
......
//主线程生成时自动通过prepareMainLooper方法为主线程创建一个Looper
//prepare()方法是用于在子线程中创建一个Looper对象,在子线程中是可以退出消息循环的:调用消息队列的quit方法
//Looper生成时会自动生成与之配套的消息队列
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
......
//loop()方法开启消息循环
//主线程的消息循环是不允许被退出的
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

MessageQueue 入队

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
boolean enqueueMessage(Message msg, long when) {
......
synchronized (this) {
......
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}

MessageQueue出队

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
Message next() {
......
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// nativePollOnce方法在native层,若是nextPollTimeoutMillis为-1,这时候消息队列处于等待状态。   
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
//按照我们设置的时间取出消息
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// 如果消息队列中没有消息,将nextPollTimeoutMillis设为-1,下次循环消息队列则处于等待状态
nextPollTimeoutMillis = -1;
}
//退出消息队列,返回null,这时候Looper中的消息循环也会终止。
if (mQuitting) {
dispose();
return null;
}
......
}
.....
}
}

ThreadLocal

线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。TLS常用的操作方法

  1. ThreadLocal.set(T value):将value存储到当前线程的TLS区域,源码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public void set(T value) {
    Thread currentThread = Thread.currentThread(); //获取当前线程
    Values values = values(currentThread); //查找当前线程的本地储存区
    if (values == null) {
    //当线程本地存储区,尚未存储该线程相关信息时,则创建Values对象
    values = initializeValues(currentThread);
    }
    //保存数据value到当前线程this
    values.put(this, value);
    }
  2. ThreadLocal.get():获取当前线程TLS区域的数据,源码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public T get() {
    Thread currentThread = Thread.currentThread();
    //获取当前线程
    Values values = values(currentThread);
    //查找当前线程的本地储存区
    if (values != null) {
    Object[] table = values.table;
    int index = hash & values.mask;
    if (this.reference == table[index]) {
    return (T) table[index + 1];
    //返回当前线程储存区中的数据
    }
    } else {
    //创建Values对象
    values = initializeValues(currentThread);
    }
    return (T) values.getAfterMiss(this);
    //从目标线程存储区没有查询是则返回null
    }